<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/06/02
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use think\Db;
use app\common\builder\ZBuilder;
/**
 * 采购单列表
 * @package app\cms\admin
 */
class Purchase extends Admin
{
    // 模型初始化
    protected static function init()
    {
        //TODO:初始化内容
    }

    /**
     * 首页
     * @author shiqiang
     * @return mixed
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        //获取筛选
        $map = $this->getMap();
        //数据获取
        $data = input();
        //数据列表
		$data_list = model('ErpGoodsPurchaseOrder', 'model') -> where($map) -> order('purchase_status asc,create_time desc') -> paginate();
		
		$btn_details = [
			'title' => '详情',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('details', ['id' => '__id__']),
		];
		
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table') // 设置页面标题
			->setPageTitle('采购单列表')
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('erp_goods_purchase_order') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['title', '采购单名称'],
                ['code', '采购单编号'],
                // ['procurement_method', '采购方式', [1=>'现购', 2=>'赊购']],
                ['arrival_days', '到货天数'],
                ['remark', '备注'],
                ['handled_by', '经办人'],
                ['purchase_status', '采购单状态', 'status', '', [1 => '采购中:warning', 2 => '已入库:success']],
                ['create_time', '创建时间', 'datetime'],
                ['right_button', '操作', 'btn']
            ])
			->setSearchArea([
                ['text', 'title', '采购单名称', 'like'],
				['text', 'code', '采购单编号', 'like'],
                ['text', 'handled_by', '经办人', 'like'],
				// ['select', 'procurement_method', '采购方式', '', '', [1 => '现购', 2=>'赊购']],
				['select', 'purchase_status', '采购单状态', '', '', [1 => '采购中', 2 => '已入库']],
            ])
            ->addTopButton('add') // 添加授权按钮
            ->addRightButton('custom', $btn_details, ['area' => ['50%', '80%']]) // 批量添加右侧按钮
            // ->addRightButton('delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面

    }

    /**
     * 添加
     * @author  shiqiang
     * @return mixed
     * @throws \think\Exception
     */
    public function add(){
		if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post('', null, 'trim');
			$url_json = [];
			$url_json['title']      			= isset($data['title']) ? $data['title'] : '';
            $url_json['supplier_id']  			= isset($data['supplier_id']) ? $data['supplier_id'] : '';
            // $url_json['procurement_method'] 	= isset($data['procurement_method']) ? $data['procurement_method'] : '';
            $url_json['procurement_method'] 	= $data['procurement_method'] = 1;
            $url_json['arrival_warehouse_id']  	= isset($data['arrival_warehouse_id']) ? $data['arrival_warehouse_id'] : '';
            // $url_json['advance_charge']  		= isset($data['advance_charge']) ? $data['advance_charge'] : '';
            $url_json['advance_charge']  		= 0;
            $url_json['arrival_days']  			= isset($data['arrival_days']) ? $data['arrival_days'] : '';
            $url_json['remark']  				= isset($data['remark']) ? $data['remark'] : '';
            $url_json['handled_by']  			= isset($data['handled_by']) ? $data['handled_by'] : '';
            $url_json['uid']  					= UID;

			//数据验证
            $Validate = validate('Purchase', 'validate');
            if( !$Validate -> scene('purchase_add') -> check($data) ){
                $this->error($Validate -> getError());
            }
			$res = model('ErpGoodsPurchaseOrderLinshi') -> isUpdate(false) ->data($url_json, true) -> save();
			$id = model('ErpGoodsPurchaseOrderLinshi') -> id;

			$this->redirect('add_goods', ['purchase_id' => $id, 'supplier_id' => $url_json['supplier_id']]);
        }
		// $warehouse_id = model('ErpWarehouse') -> where('type', 2) -> column('id,title');
		$map = [];
		$uid = UID;//后台管理员ID
		$sotre_user = model('app\user\model\User') -> find($uid);//获取列表
		
		if($sotre_user['store_uid'] > 0){
			//根据门店id 查询出仓库的id
			$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($sotre_user['store_id']);
			foreach ($warehouse_list['data'] as $key => $value) {
				if($value['type'] == 1){//分店仓库
					$store_warehouse_list[] = $value['wid'];
				}
			}
			$warehouse_id = $store_warehouse_list[0];
			$map[] = ['id', '=', $warehouse_id];
		}
		$warehouse_id = model('ErpWarehouse') -> where($map) -> column('id,title');
       // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('采购单申请') // 设置页面标题
            ->addFormItems([
					['text', 'title', '采购单名称','必填'],
					['select', 'supplier_id', '供应商', '请选择供应商', model('ErpSupplier') -> column('id,title')],
					// ['select', 'procurement_method', '采购方式', '请选择采购方式', [1 => '现购', 2=>'赊购']],
					['select', 'arrival_warehouse_id', '到货仓', '请选择到货仓', $warehouse_id, key($warehouse_id)],
					// ['text', 'advance_charge', '预付款'],
					['text', 'arrival_days', '到货天数'],
					['text', 'remark', '备注'],
					['text', 'handled_by', '经办人', '', get_nickname(UID)],
			])
			->setBtnTitle(['submit' => '下一步'])
			->isAjax(false)	
            ->fetch();
    }
	
	/**
     * 添加商品数量
     * @author  shiqiang
     * @return mixed
     * @throws \think\Exception
     */
    public function add_goods($purchase_id = [], $supplier_id = ''){
		if ($this->request->isPost()) {
			$sku_id = input('post.ids/a');
			//插入单品
			// $list = [];
			// foreach($sku_id as $sku_id){
				// $map = [];
				// $map['purchase_id'] = $purchase_id;
				// $map['sku_id'] = $sku_id;
				// $sku_linshi = model('ErpGoodsPurchaseOrderSkuLinshi') -> where($map) -> find();
				// if(empty($sku_linshi)){
					// $list[] = ['purchase_id' => $purchase_id,'sku_id' => $sku_id, 'sku_price' => $sku_info['purchase_price']];
				// }
			// }
			// $res = model('ErpGoodsPurchaseOrderSkuLinshi')->saveAll($list);
			$ids = implode(',', $sku_id);
			$this -> add_goods_sku($purchase_id, $ids);
		}
		//获取筛选
        $map = $this->getMap();
		$search = [];
		if(isset($map[0])) $search = $map[0];
			
		$map = [];
		$map['purchase_id'] = $purchase_id;
		$sku_linshi = model('ErpGoodsPurchaseOrderSkuLinshi') -> where($map) -> column('sku_id');
		
        $add_goods_sku = [
			'title' => '新增',
			'class' => 'btn btn-primary ajax-post',
            'href'  => url('add_goods',['purchase_id' => $purchase_id])
        ];
		$sku_see = [
			'title' => '已选择商品',
			'class' => 'btn btn-success',
            'href'  => url('add_goods_num',['purchase_id' => $purchase_id])
        ];

		$notid = [];
		
		$map = [];
		$map[] = ['supplier_id', '=', $supplier_id];
		$goods_id = model('ErpGoods') -> where($map) -> column('id');
		
		$map = [];
		$map[] = ['id', 'not in', $sku_linshi];
		$map[] = ['goods_id', 'in', $goods_id];
		$map[] = ['sku_status', '=', 1];
		if(!empty($search)) $map[] = $search;
		$data_list = model('ErpGoodsSku') -> where($map) -> order('create_time desc') -> paginate();//获取列表
		
		$sku_submit = [
			'title' => '新增',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-primary ajax-get',
			'href'  => url('add_goods_sku', ['purchase_id' => $purchase_id, 'ids' => '__id__']),
		];
		
        return ZBuilder::make('table') // 设置页面标题
			->setPageTitle('商品列表')
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('erp_goods_sku') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['id', '规格id'],
                ['goods_name', '商品名称'],
                ['goods_specifications', '规格'],
                ['purchase_price', '进货价格'],
				['right_button', '操作', 'btn']
            ])
            ->setSearch(['goods_name' => '商品名', 'goods_specifications' => '单品名称']) // 设置搜索参数
			->addTopButton('custom', $add_goods_sku) // 添加授权按钮
			->addTopButton('custom', $sku_see, true) // 添加授权按钮
			->addRightButton('sku_submit', $sku_submit) // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }
	
	/**
     * 新增商品
     * @author  shiqiang
     * @return mixed
     * @throws \think\Exception
     */
	public function add_goods_sku($purchase_id = '', $ids = []){
		$sku_id = explode(',', $ids);
		//插入单品
		$list = [];
		foreach($sku_id as $sku_id){
			$map = [];
			$map['purchase_id'] = $purchase_id;
			$map['sku_id'] = $sku_id;
			$sku_linshi = model('ErpGoodsPurchaseOrderSkuLinshi') -> where($map) -> find();
			if(empty($sku_linshi)){
				$sku_info = model('ErpGoodsSku') -> find($sku_id);//获取列表
				
				
				$list[] = ['purchase_id' => $purchase_id,'sku_id' => $sku_id, 'sku_price' => $sku_info['purchase_price']];
			}
		}

		$res = model('ErpGoodsPurchaseOrderSkuLinshi')->saveAll($list);
		$this->success('新增成功');
	}
	
	/**
     * 商品数量
     * @author  shiqiang
     * @return mixed
     * @throws \think\Exception
     */
    public function add_goods_num($purchase_id = []){
		$map = [];
		$map['purchase_id'] = $purchase_id;
		$data_list = model('ErpGoodsPurchaseOrderSkuLinshi') -> where($map) -> order('create_time desc') -> paginate();
		
		foreach($data_list as $key => $value){
			$sku_info = model('ErpGoodsSku') -> find($value['sku_id']);//获取列表
			$data_list[$key]['goods_name'] 				= $sku_info['goods_name'];
			$data_list[$key]['goods_specifications'] 	= $sku_info['goods_specifications'];
			$data_list[$key]['purchase_price'] 			= $sku_info['purchase_price'];
			$data_list[$key]['sku_price'] 				= $sku_info['purchase_price'];
		};
		
		$sku_delete = [
			'title' => '删除',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default ajax-get confirm',
			'href'  => url('sku_delete', ['id' => '__id__']),
			'data-title' => '确定要删除吗？'
		];
		
		$add_purchase = [
			'title' => '提交采购单',
			'class' => 'btn btn-primary ajax-get confirm',
            'href'  => url('add_purchase_submit',['purchase_id' => $purchase_id]),
        ];
		
		return ZBuilder::make('table') // 设置页面标题
			->setPageTitle('采购数量')
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('erp_goods_purchase_order_sku_linshi') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['id', '规格id'],
                ['goods_name', '商品名称'],
                ['goods_specifications', '规格名'],
                ['purchase_price', '进货价格'],
                ['sku_num', '采购数量', 'text.edit'],
                ['sku_price', '采购价格', 'text.edit'],
                ['right_button', '操作', 'btn']
            ])
			// ->hideCheckbox()
			->addTopButton('delete') // 添加顶部按钮
			->addTopButton('custom', $add_purchase) // 添加授权按钮
			->addRightButton('sku_delete', $sku_delete) // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }
	
	/**
     * 提交采购单
     * @author  shiqiang
     * @return mixed
     * @throws \think\Exception
     */
	public function add_purchase_submit($purchase_id = ''){
		DB::startTrans();//启动事务
		$purchase_linshi = model('ErpGoodsPurchaseOrderLinshi') -> find($purchase_id); // 采购单详情
		$sku_linshi = model('ErpGoodsPurchaseOrderSkuLinshi') -> where('purchase_id', $purchase_id) -> column('id,sku_id,sku_num,sku_price'); // 采购单详情
		if(empty($sku_linshi)){
			DB::rollback();
			$this->error('请选择需要采购的商品');
		}
		$user_id 				= $purchase_linshi['uid'];
		$title 					= $purchase_linshi['title'];
		$supplier_id 			= $purchase_linshi['supplier_id'];
		$procurement_method 	= $purchase_linshi['procurement_method'];
		$arrival_warehouse_id 	= $purchase_linshi['arrival_warehouse_id'];
		$advance_charge 		= $purchase_linshi['advance_charge'];
		$arrival_days 			= $purchase_linshi['arrival_days'];
		$remark 				= $purchase_linshi['remark'];
		$handled_by 			= $purchase_linshi['handled_by'];
		
		$order_num = model('ErpGoodsPurchaseOrder', 'model') -> count();
		$order_num = $order_num + 1;
		$code = 'P' . date('Ymd') . str_pad($order_num, 3, '0', STR_PAD_LEFT);//拼接code  规则 P + 日期 + 流水号 (本日订单总数 + 1) 3位数 补0

        //获取回款日期
        if(!empty($supplier_id)){
            $supplier_infos = model('ErpSupplier','model') ->where('id',$supplier_id)-> column('id,settlement_cycle,jiesuan_date,jiesuan_type');
            $supplier_info = $supplier_infos[$supplier_id];
            if($supplier_info['jiesuan_type'] == 3){
                // 月结 次月 固定日期
                $back_date = strtotime(date('Y-m',strtotime('next month')).'-'.$supplier_info['jiesuan_date']);
                $a = date('Y-m',strtotime('next month')).'-'.$supplier_info['jiesuan_date'];
            }elseif ($supplier_info['jiesuan_type'] == 2){
                // 月结 当月 固定日期
                $back_date = strtotime(date('Y-m',time()).'-'.$supplier_info['jiesuan_date']);
            }else{
                $back_date = '';
            }
            if(!empty($back_date) && $back_date < time() && $supplier_info['jiesuan_type'] > 1){
                $this->error('回款时间不能小于当前时间');
            }
        }
		$rel = model('ErpGoodsPurchaseOrder', 'model') -> addData($user_id, $title, $supplier_id, $procurement_method, $arrival_warehouse_id, $advance_charge, $arrival_days, $remark, $handled_by, $code, $back_date);
		if($rel['code'] < 0){
			DB::rollback();
			$this->error($rel['message'], cookie('__forward__'));
		}
		
		//插入采购单 sku参数
		$sku_arr = [];
		$sku_linshi_id = [];
		$p_id = $rel['data'];
		foreach($sku_linshi as $key => $value){
			if($value['sku_num'] == 0){
				DB::rollback();
				$this->error('请输入采购单所有商品的采购数量');
			}
			$sku_info = model('ErpGoodsSku') -> find($value['sku_id']);//获取列表
			$sku_arr[] = [
				'purchase_id' => $p_id,
				'sku_id'	  => $value['sku_id'],
				'num'	  	  => $value['sku_num'],
				'price'	  	  => $value['sku_price'],
			];
			$sku_linshi_id[] = $key;
		}
		
		$rel = model('ErpGoodsPurchaseOrderSku') -> saveAll($sku_arr);//dump($rel);

		if(!$rel < 0){
			DB::rollback();
			$this->error('插入失败，请重试', cookie('__forward__'));
		}
		
		model('ErpGoodsPurchaseOrderLinshi') -> destroy($purchase_id);
		model('ErpGoodsPurchaseOrderSkuLinshi') -> destroy($sku_linshi_id);
		
		DB::commit();
		$this->success('采购单创建成功', url('purchase_warehousing/index'), '_parent_reload');
	}
	
	/*
	 * 删除
	*/
	public function sku_delete($id = '', $ids = []){
		// $linshi_sku_id = model('ErpGoodsPurchaseOrderSkuLinshi') -> find($id) -> sku_id;
		// $sku_id = explode(',', $ids);
		// $new_ids = [];
		// foreach($sku_id as $key => $value){
			// if($value != $linshi_sku_id){
				// $new_ids[] = $value;
			// }
		// }
		$res = model('ErpGoodsPurchaseOrderSkuLinshi') -> destroy($id);
		if(!$res){
			$this->error('删除失败');
		}else{
			// $new_ids = implode(',', $new_ids);
			// $url = explode('?', cookie('__forward__'));
			// $url = $url[0] . '?ids=' . $new_ids;
			// $this->success('删除成功', $url);
			$this->success('删除成功');
		}
	}
	
	//采购单详情
	public function details($id = []){
		$info = model('ErpGoodsPurchaseOrder') -> find($id);
		$info['supplier_title'] 	= model('ErpSupplier') -> find($info['supplier_id']) -> title;
		// $info['procurement_method'] = $info['procurement_method'] == 1 ? '现购' : '赊购';
		$info['arrival_warehouse']= model('ErpWarehouse') -> find($info['arrival_warehouse_id']) -> title;
		
		$table_data = [
			['sku_id', '采购商品', '价格', '数量'],
		];
		$purchase_sku = model('ErpGoodsPurchaseOrderSku') -> where('purchase_id', $id) -> column('sku_id,num,price');
		foreach($purchase_sku as $value){
			$goods_info = model('ErpGoodsSku') -> find($value['sku_id']);
			if($goods_info['goods_specifications'] != ''){
				$goods_name = $goods_info['goods_name'] . ' - ' . $goods_info['goods_specifications'];
			}else{
				$goods_name = $goods_info['goods_name'];
			}
			
			$table_data[] = [$value['sku_id'], $goods_name, $value['price'], $value['num']];
		}
		
		//批量审核最多允许20个
		return ZBuilder::make('form')
            ->setPageTitle('采购单详情') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
				['text', 'title', '采购单名称', '', '', '', 'readonly="readonlys"'],
				['text', 'supplier_title', '供应商', '', '', '', 'readonly="readonlys"'],
				// ['text', 'procurement_method', '采购方式', '', '', '', 'readonly="readonlys"'],
				['text', 'arrival_warehouse', '到货仓', '', '', '', 'readonly="readonlys"'],
				// ['text', 'advance_charge', '预付款', '', '', '', 'readonly="readonlys"'],
				['text', 'arrival_days', '到货天数', '', '', '', 'readonly="readonlys"'],
				['text', 'remark', '备注', '', '', '', 'readonly="readonlys"'],
				['text', 'handled_by', '经办人', '', '', '', 'readonly="readonlys"'],
			])
			->addFormItems([ // 批量添加表单项
				['complexTable', 'list_user', '采购单sku', $table_data]
			])
			->hideBtn(['submit', 'back'])
			->setFormData($info) // 设置表单数据
            ->fetch();
	}
	
	// public function quickedit($record = []){
		
	// }
}